package com.wgy.cn;

import java.io.File;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.Date;

public class FileTools {
    public static PrintStream old = System.out;

    public static void printLog(PrintStream ps, String str) {
        System.setOut(ps);
        System.out.println(str);
    }

    public static void printControl(String str) {
        System.setOut(old);
        System.out.println(str);
    }

    public static long getDistDates(Date startDate, Date endDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long timestart = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long timeend = calendar.getTimeInMillis();
        return Math.abs((timeend - timestart)) / (1000 * 60 * 60 * 24);
    }

    public static long logdays(String str) {
        return (long) (Double.parseDouble(str));
    }

    public static void delete(File file, String days, PrintStream ps) {
        // 日志保留时间
        Calendar cal = Calendar.getInstance();
        Date lastModified;
        Date startDate = new Date();
        // 列出文件夹下的所有资源
        File[] fs = file.listFiles();
        if (fs != null) {
            for (File f : fs) {
                cal.setTimeInMillis(f.lastModified());
                lastModified = cal.getTime();
                if (f.isFile()) {
                    if (getDistDates(startDate, lastModified) > logdays(days)) {
                        if(f.delete()){
                            FileTools.printControl("<" + f + ">" + "已清理");
                            FileTools.printLog(ps, "<" + f + ">" + "已清理");
                        }else {
                            System.out.println("文件清理失败！");
                        }
                    }
                } else {
                    if (getDistDates(startDate, lastModified) > logdays(days)) {
                        delete(f, days, ps);
                        if(f.delete()){
                            FileTools.printControl("<" + f + ">" + "已清理");
                            FileTools.printLog(ps, "<" + f + ">" + "已清理");
                        }else {
                            System.out.println("文件清理失败");
                        }
                    }
                }
            }
        }
    }

}
